<template>
  <div class="data-list-tree">
    <div class="data-list-top">
      <span>{{ $t('rootPage.dataList') }}</span>
      <el-tooltip :content="$t('rootPage.newQueryWindow')" :visible-arrow="false" effect="light">
        <div class="icon-1">
          <svg class="icon" aria-hidden="true" @click="btnClick1" v-icon="`#icon-xinjianchaxun-color`">
            <use xlink:href="#icon-xinjianchaxun"></use>
          </svg>
        </div>
      </el-tooltip>
      <el-tooltip :content="$t('rootPage.newdatasource')" :visible-arrow="false" effect="light">
        <div class="icon-2">
          <svg v-icon="`#icon-xinzengshujulianjie-color`" class="icon" aria-hidden="true" @click="newSource">
            <use xlink:href="#icon-xinzengshujulianjie"></use>
          </svg>
        </div>
      </el-tooltip>
    </div>
    <!-- <div class="data-list-input">
      <el-input size="small" placeholder="" v-model="searchVal">
        <template #suffix>
          <i @click="searchClick" class="el-icon-search"></i>
        </template>
      </el-input>
    </div> -->
    <el-tree
      v-if="store.state?.userInfo?.userId !== undefined"
      ref="treeRef"
      highlight-current
      node-key="id"
      :indent="20"
      :props="treeProps"
      @node-click="nodeClick"
      :load="loadNode"
      lazy
      :current-node-key="nodekey"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <icon-types :data="data" :nodekey="nodekey" />
          <span>{{ node.label }}</span>
        </span>
      </template>
    </el-tree>
    <NewSource v-if="showDialog" :serverId="null" :showDialog="showDialog" :types="types" @close="close()" />
  </div>
</template>

<script>
import { ElTree, ElTooltip } from 'element-plus';
import { reactive, ref } from 'vue';
import { useStore } from 'vuex';
import IconTypes from './iconTypes.vue';
import axios from '@/util/axios.js';
import NewSource from '../../Source/components/newSource';

export default {
  name: 'DataListTree',
  props: ['handleNodeClick', 'nodekey'],
  setup(props) {
    const treeProps = reactive({
      label: 'name',
      children: 'zones',
      isLeaf: 'leaf',
      disabled: 'disabled',
    });
    const searchVal = ref('');
    const treeRef = ref(null);
    const store = useStore();
    const showDialog = ref(false);
    const types = ref(null);
    const searchClick = () => {
      console.log('jj');
    };

    const nodeClick = (data, node) => {
      props.handleNodeClick(data, node);
    };
    /**
     * 新建数据源
     */
    const newSource = () => {
      showDialog.value = true;
      types.value = 0;
    };
    /**
     * 关闭或者取消新增/编辑数据连接操作
     */
    const close = () => {
      showDialog.value = false;
      types.value = 0;
    };
    const btnClick2 = () => {};

    const loadNode = (node, resolve) => {
      if (node.level === 0) {
        axios.get('/servers', { params: { userId: store.state?.userInfo?.userId } }).then((res) => {
          if (res?.code === '0') {
            let data = (res.data.aliasList || []).map((e) => {
              return {
                name: e.alias,
                id: e.id + 'connection',
                type: 'connection',
                rawid: e.id,
                connectionid: e.id,
              };
            });
            return resolve(data);
          }
        });
      }
      if (node.level === 1) {
        axios.get(`/servers/${node.data.rawid}/storageGroups`, {}).then((res) => {
          let newStorageGroup = {
            id: node.data.id + ':newstoragegroup',
            name: '新建存储组',
            parent: node.data,
            type: 'newstorageGroup',
            leaf: true,
            connectionid: node.data.connectionid,
          };
          let queryList = {
            id: node.data.id + ':querylist',
            name: '查询',
            parent: node.data,
            type: 'querylist',
            connectionid: node.data.connectionid,
          };
          if (res?.code === '0') {
            let data = (res.data || []).map((e) => {
              return {
                parent: node.data,
                name: e.groupName,
                id: e.groupName + 'storageGroup',
                type: 'storageGroup',
                rawid: e.groupName,
                storagegroupid: e.groupName,
                connectionid: node.data.connectionid,
              };
            });
            data.unshift(queryList);
            data.unshift(newStorageGroup);
            return resolve(data);
          }
        });
      }
      if (node.level === 2 && node.data.type === 'storageGroup') {
        let groupName = node.data.rawid;
        let serverId = node.data.parent.rawid;
        axios.get(`/servers/${serverId}/storageGroups/${groupName}/devices`, {}).then((res) => {
          let newDevice = {
            id: node.data.id + ':newdevice',
            name: '新建实体',
            type: 'newdevice',
            leaf: true,
            parent: node.data,
            connectionid: node.data.connectionid,
            storagegroupid: node.data.storagegroupid,
          };
          if (res?.code === '0') {
            let data = (res.data || []).map((e) => {
              return {
                parent: node.data,
                name: e,
                id: e + 'device',
                type: 'device',
                leaf: true,
                rawid: e,
                storagegroupid: node.data.storagegroupid,
                connectionid: node.data.connectionid,
                deviceid: e,
              };
            });
            data.unshift(newDevice);
            return resolve(data);
          }
        });
      }
      if (node.level === 2 && node.data.type === 'querylist') {
        let serverId = node.data.parent.rawid;
        axios.get(`/servers/${serverId}/query`, {}).then((res) => {
          let newQuery = {
            id: node.data.id + ':newquery',
            name: '新建查询',
            type: 'newquery',
            leaf: true,
            parent: node.data,
            storagegroupid: node.data.storagegroupid,
            connectionid: node.data.connectionid,
          };
          if (res?.code === '0') {
            let data = (res.data || []).map((e) => {
              return {
                parent: node.data,
                name: e.queryName,
                id: e.id + 'query',
                type: 'query',
                leaf: true,
                rawid: e.id,
                storagegroupid: node.data.storagegroupid,
                connectionid: node.data.connectionid,
                queryid: e.id,
              };
            });
            data.unshift(newQuery);
            return resolve(data);
          }
        });
      }
    };

    return {
      store,
      loadNode,
      searchClick,
      nodeClick,
      newSource,
      btnClick2,
      treeProps,
      searchVal,
      treeRef,
      close,
      showDialog,
      types,
    };
  },
  components: {
    ElTree,
    IconTypes,
    // ElInput,
    ElTooltip,
    NewSource,
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.data-list-tree {
  height: 100%;
  overflow: auto;
  .data-list-top {
    color: rgba(34, 34, 34, 0.65);
    font-size: 12px;
    line-height: 20px;
    text-align: left;
    margin: 15px 20px;
    position: relative;
    .icon {
      font-size: 16px;
      cursor: pointer;
    }
    .icon-1 {
      top: 2px;
      right: 0px;
      position: absolute;
    }
    .icon-2 {
      top: 2px;
      right: 30px;
      position: absolute;
    }
  }
  .data-list-input {
    margin: 0 20px 15px;
  }
  &::v-deep .el-tree {
    height: calc(100% - 50px);
    width: 100%;
    overflow: auto;
    .el-tree-node {
      min-width: fit-content;
    }
    .el-tree-node__content {
      min-width: fit-content;
    }
  }
}
</style>
